//
//  PullRefreshAndLoadMoreViewController.m
//  Paparazzi
//
//  Created by papo on 12/5/13.
//
//

#import "PullRefreshAndLoadMoreViewController.h"

@interface PullRefreshAndLoadMoreViewController ()
{
    UIView* loadingFooterView;
    UIActivityIndicatorView*    loadingActivyIndicator;
    
}
@end

@implementation PullRefreshAndLoadMoreViewController
@synthesize isLoadingMore;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self addLoadingFooterView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addLoadingFooterView
{
    loadingFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, REFRESH_HEADER_HEIGHT)];
    loadingFooterView.backgroundColor = [UIColor clearColor];
    

    loadingActivyIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [loadingActivyIndicator setCenter:CGPointMake(160, REFRESH_HEADER_HEIGHT / 2)];
    [loadingActivyIndicator setHidesWhenStopped:YES];
    
    [loadingFooterView addSubview:loadingActivyIndicator];
    [self.tableView setTableFooterView:loadingFooterView];
    self.tableView.tableFooterView.hidden = YES;
}

//

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [super scrollViewDidScroll:scrollView];
    if (!isLoadingMore && !isLoading && scrollView.contentOffset.y >= scrollView.contentSize.height - scrollView.frame.size.height && scrollView.contentSize.height > scrollView.frame.size.height)
    {
        [self startLoadingMore];
    }
}

- (void)startLoadingMore
{
    isLoadingMore = YES;
    self.tableView.tableFooterView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        [loadingActivyIndicator startAnimating];
        
    }];
    [self loadingMore];
}

- (void)stopLoadingMore
{
    isLoadingMore = NO;
    [loadingActivyIndicator stopAnimating];
    self.tableView.tableFooterView.hidden = YES;
}

// override refresh method
- (void)refresh
{
    if ([self.delegate respondsToSelector:@selector(pullRefreshTableViewRefresh)]) {
        [self.delegate pullRefreshTableViewRefresh];
        return;
    }
}

- (void)loadingMore
{
    if ([self.delegate respondsToSelector:@selector(pullRefreshTableViewLoadingMore)]) {
        [self.delegate pullRefreshTableViewLoadingMore];
    }
}

@end
